#include "gif.h"

#ifdef __cplusplus
extern "C"{
#endif

JNIEXPORT void JNICALL
Java_pl_droidsonroids_gif_GifInfoHandle_free(JNIEnv *env, jclass handleClass, jlong gifInfo) {
    GifInfo *info = (GifInfo *) (intptr_t) gifInfo;
    if (info == NULL) {
        return;
    }
    if (info->destructor != NULL) {
        info->destructor(info, env);
    }
    if (info->rewindFunction == streamRewind) {
        StreamContainer *streamContainer = (StreamContainer *)info->gifFilePtr->UserData;

        env->CallVoidMethod(streamContainer->stream, streamContainer->closeMethodID);

        if (env->ExceptionCheck() == JNI_TRUE) {
#ifdef DEBUG
            (*env)->ExceptionDescribe(env);
#endif
            env->ExceptionClear();
        }

        env->DeleteGlobalRef(streamContainer->stream);
        env->DeleteGlobalRef(streamContainer->buffer);

        free(streamContainer);
    } else if (info->rewindFunction == fileRewind) {
        fclose((FILE *)info->gifFilePtr->UserData);
    } else if (info->rewindFunction == byteArrayRewind) {
        ByteArrayContainer *container = (ByteArrayContainer *)info->gifFilePtr->UserData;
        env->DeleteGlobalRef(container->buffer);
        free(container);
    } else if (info->rewindFunction == directByteBufferRewind) {
        DirectByteBufferContainer *container = (DirectByteBufferContainer *)info->gifFilePtr->UserData;
        env->DeleteGlobalRef(container->bufferRef);
        free(container);
    }
    info->gifFilePtr->UserData = NULL;
    cleanUp(info);
    return ;
}

void cleanUp(GifInfo *info) {
    free(info->backupPtr);
    info->backupPtr = NULL;
    free(info->controlBlock);
    info->controlBlock = NULL;
    free(info->rasterBits);
    info->rasterBits = NULL;
    free(info->comment);
    info->comment = NULL;

    DGifCloseFile(info->gifFilePtr);
    free(info);
}
#ifdef __cplusplus
}
#endif